package paythere

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/logic/pay"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/pay/paythere"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/assets-api/pkg/consts"
	"gitee.com/liuxuezhan/ar-platform/assets-api/pkg/xerrors"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/bytedance/sonic"
	"github.com/zeromicro/go-zero/core/logc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PayTherePaymentNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// PayThere代收回调通知
func NewPayTherePaymentNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PayTherePaymentNotifyLogic {
	return &PayTherePaymentNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PayTherePaymentNotifyLogic) PayTherePaymentNotify(req *types.PayTherePaymentNotifyReq) (resp *types.PayTherePaymentNotifyResp, err error) {

	logc.Info(l.ctx, "---------------------------------------")
	b, _ := sonic.Marshal(req)
	logc.Info(l.ctx, string(b))
	// 获取 payfun 配置信息
	conf, err := l.svcCtx.AssetsRpc.PayRecharge.RechargeChannelListByCode(l.ctx, &rpc.RechargeChannelByCodeRequest{Code: consts.PayThereCode})
	if err != nil {
		return nil, err
	}
	// 请求参数
	params := map[string]any{
		"amount":          req.Amount,
		"factAmount":      req.FactAmount,
		"merchantNo":      req.MerchantNo,
		"merchantOrderNo": req.MerchantOrderNo,
		"platOrderNo":     req.PlatOrderNo,
		"orderStatus":     req.OrderStatus,
		"orderMessage":    req.OrderMessage,
	}
	// 生成签名
	sign, err := paythere.GenerateSignature(params, conf.SecretKey)
	if err != nil {
		return nil, err
	}
	if sign != req.Sign {
		return nil, xerrors.ErrSignVerifyFailed
	}
	// 根据订单状态处理业务逻辑
	switch req.OrderStatus {
	case "ARRIVED", "SUCCESS", "CLEARED":
		_, err = l.svcCtx.AssetsRpc.PayRecharge.RechargeSuccess(l.ctx, &rpc.NotifyOKRequest{OrderNo: req.MerchantOrderNo, ReturnJson: string(b)})
		if err != nil {
			logc.Error(l.ctx, err, string(b))
			return
		}
		pay.NewHandleOrderLogic(l.ctx, l.svcCtx).AddNotifitionMessage(&pay.NotifyMessageInfo{
			OrderNo: req.MerchantOrderNo,
		})

		resp = &types.PayTherePaymentNotifyResp{Ok: true}
	case "FAILED":
		_, err = l.svcCtx.AssetsRpc.PayRecharge.RechargeFail(l.ctx, &rpc.NotifyFailRequest{OrderNo: req.MerchantOrderNo, ReturnJson: string(b)})
		if err != nil {
			logc.Error(l.ctx, err, string(b))
			return
		}
		resp = &types.PayTherePaymentNotifyResp{Ok: false}
	default:
		resp = &types.PayTherePaymentNotifyResp{Ok: false}
	}
	return
}
